<template>
    <el-dialog :model-value="visible" :title="isEdit ? '编辑策略' : '创建新策略'"
        @update:model-value="$emit('update:visible', $event)" width="60%">
        <el-form :model="form" ref="strategyFormRef" label-width="120px" :rules="rules">
            <el-form-item label="策略名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入策略名称"></el-input>
            </el-form-item>
            <el-form-item label="策略类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择策略类型">
                    <el-option label="大类资产配置" value="ASSET_ALLOCATION"></el-option>
                    <el-option label="FOF组合" value="FOF"></el-option>
                    <el-option label="指数组合" value="INDEX"></el-option>
                    <el-option label="择时组合" value="TIMING"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="风险等级" prop="riskLevel">
                <el-input v-model="form.riskLevel" placeholder="例如: R1, R2, R3..."></el-input>
            </el-form-item>
            <el-form-item label="业绩比较基准" prop="benchmark">
                <el-input v-model="form.benchmark" placeholder="例如: 沪深300"></el-input>
            </el-form-item>
            <el-form-item label="适用人群" prop="targetAudience">
                <el-input type="textarea" v-model="form.targetAudience" placeholder="描述该策略适合的投资者类型"></el-input>
            </el-form-item>
            <el-form-item label="策略描述" prop="description">
                <el-input type="textarea" v-model="form.description" placeholder="详细描述策略的投资逻辑和目标"></el-input>
            </el-form-item>

            <el-divider>再平衡规则</el-divider>
            <el-form-item label="规则类型" prop="rebalanceRule.type">
                <el-select v-model="form.rebalanceRule.type" placeholder="请选择再平衡规则类型" clearable>
                    <el-option label="周期调仓" value="PERIODIC"></el-option>
                    <el-option label="阈值调仓" value="THRESHOLD"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item v-if="form.rebalanceRule.type === 'PERIODIC'" label="调仓频率" prop="rebalanceRule.frequency">
                <el-select v-model="form.rebalanceRule.frequency" placeholder="请选择调仓频率">
                    <el-option label="每周" value="WEEKLY"></el-option>
                    <el-option label="每月" value="MONTH"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item v-if="form.rebalanceRule.type === 'THRESHOLD'" label="调仓阈值(%)" prop="rebalanceRule.threshold">
                <el-input-number v-model="form.rebalanceRule.threshold" :precision="2" :step="0.5" :min="0"
                    placeholder="请输入阈值"></el-input-number>
            </el-form-item>
            <div v-if="!isEdit">
                <el-divider>成分基金</el-divider>
                <div v-for="(component, index) in form.components" :key="index" class="component-item">
                    <el-form-item :label="'基金 ' + (index + 1)" :prop="'components.' + index + '.fundCode'"
                        :rules="{ required: true, message: '基金代码不能为空', trigger: 'blur' }">
                        <el-input v-model="component.fundCode" placeholder="基金代码"
                            style="width: 40%; margin-right: 10px;"></el-input>
                        <el-input-number v-model="component.weight" placeholder="权重(%)" :precision="2" :step="1"
                            :min="0" :max="100" style="width: 40%; margin-right: 10px;"></el-input-number>
                        <el-button @click.prevent="removeComponent(index)" type="danger" link>删除</el-button>
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button @click="addComponent" type="primary" plain>新增基金</el-button>
                </el-form-item>
            </div>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="$emit('update:visible', false)">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, watch, reactive } from 'vue';
import { ElMessage } from 'element-plus';

const props = defineProps({
    visible: Boolean,
    strategyData: Object,
});

const emit = defineEmits(['update:visible', 'saved']);

const isEdit = ref(false);
const form = ref({
    rebalanceRule: {} // 确保 rebalanceRule 对象存在
});
const strategyFormRef = ref(null);

const rules = reactive({
    name: [{ required: true, message: '策略名称不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '策略类型不能为空', trigger: 'change' }],
    riskLevel: [{ required: true, message: '风险等级不能为空', trigger: 'blur' }],
    'rebalanceRule.type': [{ required: true, message: '规则类型不能为空', trigger: 'change' }],
    'rebalanceRule.frequency': [{ required: true, message: '调仓频率不能为空', trigger: 'change' }],
    'rebalanceRule.threshold': [{ required: true, message: '调仓阈值不能为空', trigger: 'blur' }],
});

watch(() => props.visible, (newVal) => {
    if (newVal) {
        isEdit.value = !!props.strategyData?.id;
        const sourceData = props.strategyData ? JSON.parse(JSON.stringify(props.strategyData)) : {};

        if (isEdit.value) {
            const { components, ...restOfStrategy } = sourceData;
            form.value = {
                ...restOfStrategy,
                rebalanceRule: restOfStrategy.rebalanceRule || {}, // 确保 rebalanceRule 对象存在
                components: components ? components.map(c => ({
                    fundCode: c.fund.code,
                    weight: c.weight
                })) : []
            };
        } else {
            form.value = {
                name: '',
                type: '',
                description: '',
                targetAudience: '',
                benchmark: '',
                riskLevel: '',
                rebalanceRule: {}, // 新建时初始化为空对象
                components: [{ fundCode: '', weight: null }]
            };
        }
    }
});


const addComponent = () => {
    form.value.components.push({
        fundCode: '',
        weight: null
    });
};

const removeComponent = (index) => {
    form.value.components.splice(index, 1);
};


const submitForm = () => {
    strategyFormRef.value.validate((valid) => {
        if (valid) {
            if (!isEdit.value) {
                const totalWeight = form.value.components.reduce((sum, item) => sum + (item.weight || 0), 0);
                if (Math.abs(totalWeight - 100) > 0.01) {
                    ElMessage.error('所有成分基金的权重总和必须等于 100%');
                    return;
                }
            }

            // 清理无用的再平衡规则数据
            const dataToSave = { ...form.value };
            if (dataToSave.rebalanceRule.type === 'PERIODIC') {
                delete dataToSave.rebalanceRule.threshold;
            } else if (dataToSave.rebalanceRule.type === 'THRESHOLD') {
                delete dataToSave.rebalanceRule.frequency;
            }

            emit('saved', dataToSave, isEdit.value);
        } else {
            ElMessage.error('请填写所有必填项');
            return false;
        }
    });
};
</script>

<style scoped>
.component-item {
    margin-bottom: 18px;
}
</style>